package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName SeckillSkuScheduled
 * @Description TODO
 * @Detail 在服务空闲的时候，商品定时上架
 *              1、如每天凌晨三点，我们提前上架三天的产品，可用于秒杀商品预热
 *                  当天 00:00-23:59
 *                  第二天 00:00-23:59
 *                  第三天 00:00-23:59
 * @Author MyPC
 * @Date 2020/7/27
 * @Version 1.0
 */
@Slf4j
@Service
public class SeckillSkuScheduled {

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    private final String upload_lock="seckill:upload:lock";

    /**
     * 定时上架三天的秒杀商品
     */
    @Scheduled(cron = "*/3 * * * * ?")
    public void UploadSeckillSkuLatest3Days(){
        System.out.println("上架秒杀商品");
        //分布式锁保证只有一个线程操作redis
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            //重复上架无需处理,保证幂等即可
            seckillService.UploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }
    }
}
